<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>风险详情</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="container mt-4" 
         th:data-risk-id="${risk.id}" 
         th:data-project-id="${project.id}" 
         id="page-data-container">
        <div class="row mb-3">
            <div class="col">
                <h2>风险详情</h2>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a th:href="@{/project/list}">项目列表</a></li>
                        <li class="breadcrumb-item"><a th:href="@{/risk/project/{id}(id=${project.id})}">项目风险</a></li>
                        <li class="breadcrumb-item active" aria-current="page">风险详情</li>
                    </ol>
                </nav>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">风险信息</h5>
                        <div>
                            <a th:href="@{/risk-history/risk/{id}(id=${risk.id})}" class="btn btn-sm btn-info">
                                <i class="fa fa-history"></i> 历史记录
                            </a>
                            <a th:href="@{/risk/edit/{id}(id=${risk.id})}" class="btn btn-sm btn-primary" sec:authorize="hasAnyRole('ADMIN', 'MANAGER')">
                                <i class="fa fa-edit"></i> 编辑
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th style="width: 30%">风险标题:</th>
                                        <td th:text="${risk.title}"></td>
                                    </tr>
                                    <tr>
                                        <th>风险类型:</th>
                                        <td>
                                            <span th:if="${risk.type == 1}">技术风险</span>
                                            <span th:if="${risk.type == 2}">管理风险</span>
                                            <span th:if="${risk.type == 3}">商业风险</span>
                                            <span th:if="${risk.type == 4}">外部风险</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>风险级别:</th>
                                        <td>
                                            <span th:if="${risk.level == 1}" class="badge badge-info">低</span>
                                            <span th:if="${risk.level == 2}" class="badge badge-warning">中</span>
                                            <span th:if="${risk.level == 3}" class="badge badge-danger">高</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>可能性:</th>
                                        <td>
                                            <span th:if="${risk.probability == 1}">低</span>
                                            <span th:if="${risk.probability == 2}">中</span>
                                            <span th:if="${risk.probability == 3}">高</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>影响程度:</th>
                                        <td>
                                            <span th:if="${risk.impact == 1}">低</span>
                                            <span th:if="${risk.impact == 2}">中</span>
                                            <span th:if="${risk.impact == 3}">高</span>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th style="width: 30%">状态:</th>
                                        <td>
                                            <span th:if="${risk.status == 1}" class="badge badge-secondary">已识别</span>
                                            <span th:if="${risk.status == 2}" class="badge badge-primary">已分析</span>
                                            <span th:if="${risk.status == 3}" class="badge badge-info">已计划</span>
                                            <span th:if="${risk.status == 4}" class="badge badge-warning">已处理</span>
                                            <span th:if="${risk.status == 5}" class="badge badge-success">已解决</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>提出人:</th>
                                        <td th:text="${proposer != null ? proposer.realName : '未知'}"></td>
                                    </tr>
                                    <tr>
                                        <th>责任人:</th>
                                        <td th:text="${owner != null ? owner.realName : '未指定'}"></td>
                                    </tr>
                                    <tr>
                                        <th>创建时间:</th>
                                        <td th:text="${#dates.format(risk.createTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
                                    </tr>
                                    <tr>
                                        <th>更新时间:</th>
                                        <td th:text="${#dates.format(risk.updateTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        
                        <div class="row mt-3">
                            <div class="col-12">
                                <h6>风险描述:</h6>
                                <p class="border p-3 bg-light" th:text="${risk.description != null && !risk.description.isEmpty() ? risk.description : '暂无描述'}"></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">风险响应计划</h5>
                        <a th:href="@{/risk-response/add(riskId=${risk.id})}" class="btn btn-sm btn-success" sec:authorize="hasAnyRole('ADMIN', 'MANAGER')">
                            <i class="fa fa-plus"></i> 添加响应计划
                        </a>
                    </div>
                    <div class="card-body">
                        <div id="response-plans-container">
                            <div class="text-center py-3">
                                <i class="fa fa-spinner fa-spin fa-2x"></i>
                                <p class="mt-2">加载响应计划数据...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 风险附件管理部分 -->
        <div class="row mb-3">
            <div class="col">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">风险附件</h5>
                        <div>
                            <a th:href="@{/risk/{id}/attachments(id=${risk.id})}" class="btn btn-sm btn-secondary mr-2">
                                <i class="fa fa-list"></i> 管理附件
                            </a>
                            <button class="btn btn-sm btn-primary" onclick="$('#uploadAttachmentModal').modal('show')">
                                <i class="fa fa-upload"></i> 上传附件
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="attachment-container">
                            <div class="text-center py-3">
                                <i class="fa fa-spinner fa-spin fa-2x"></i>
                                <p class="mt-2">加载附件数据...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row" sec:authorize="hasAnyRole('ADMIN', 'MANAGER')">
            <div class="col">
                <div class="card">
                    <div class="card-header">风险管理</div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>更新风险状态:</label>
                                    <div class="btn-group btn-group-sm">
                                        <button type="button" class="btn btn-secondary" onclick="updateStatus(1)" th:disabled="${risk.status == 1}">已识别</button>
                                        <button type="button" class="btn btn-primary" onclick="updateStatus(2)" th:disabled="${risk.status == 2}">已分析</button>
                                        <button type="button" class="btn btn-info" onclick="updateStatus(3)" th:disabled="${risk.status == 3}">已计划</button>
                                        <button type="button" class="btn btn-warning" onclick="updateStatus(4)" th:disabled="${risk.status == 4}">已处理</button>
                                        <button type="button" class="btn btn-success" onclick="updateStatus(5)" th:disabled="${risk.status == 5}">已解决</button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>指定责任人:</label>
                                    <div class="input-group">
                                        <select id="ownerId" class="form-control">
                                            <option value="">-- 请选择责任人 --</option>
                                            <option th:each="user : ${users}" 
                                                    th:value="${user.id}" 
                                                    th:text="${user.realName}"
                                                    th:selected="${risk.ownerId != null && risk.ownerId == user.id}"></option>
                                        </select>
                                        <div class="input-group-append">
                                            <button class="btn btn-primary" type="button" onclick="assignOwner()">指定</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col">
                                <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                                    <i class="fa fa-trash"></i> 删除风险
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 附件上传模态框 -->
    <div class="modal fade" id="uploadAttachmentModal" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadModalLabel">上传附件</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="attachmentForm" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="attachmentFile">选择文件</label>
                            <input type="file" class="form-control-file" id="attachmentFile" name="file" required>
                            <small class="form-text text-muted">支持文档、图片等文件，最大10MB</small>
                        </div>
                    </form>
                    <div class="progress mt-3" style="display: none;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="uploadBtn">上传</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>确定要删除风险 <span th:text="${risk.title}"></span> 吗？此操作不可恢复！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="deleteRisk()">删除</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 获取风险ID和项目ID
        const riskId = $('#page-data-container').data('riskId');
        const projectId = $('#page-data-container').data('projectId');
        
        $(document).ready(function() {
            loadResponsePlans();
            loadAttachments();
            
            // 附件上传处理
            $('#uploadBtn').click(function() {
                const fileInput = $('#attachmentFile')[0];
                if (fileInput.files.length === 0) {
                    alert('请选择文件');
                    return;
                }
                
                const formData = new FormData();
                formData.append('file', fileInput.files[0]);
                
                // 显示进度条
                $('.progress').show();
                
                $.ajax({
                    url: '/risk-management/api/risk-attachments/' + riskId + '/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    xhr: function() {
                        const xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function(evt) {
                            if (evt.lengthComputable) {
                                const percentComplete = evt.loaded / evt.total * 100;
                                $('.progress-bar').css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function(response) {
                        $('#uploadAttachmentModal').modal('hide');
                        loadAttachments();
                        // 重置表单和进度条
                        $('#attachmentForm')[0].reset();
                        $('.progress').hide();
                        $('.progress-bar').css('width', '0%');
                    },
                    error: function(xhr) {
                        alert('上传失败: ' + (xhr.responseJSON ? xhr.responseJSON.message : '未知错误'));
                        $('.progress').hide();
                    }
                });
            });
        });
        
        // 加载附件数据
        function loadAttachments() {
            $.ajax({
                url: '/risk-management/api/risk-attachments/' + riskId,
                type: 'GET',
                dataType: 'json',
                success: function(attachments) {
                    let html = '';
                    if (attachments && attachments.length > 0) {
                        html = '<div class="table-responsive">' +
                               '<table class="table table-hover">' +
                               '<thead><tr>' +
                               '<th>文件名</th><th>类型</th><th>大小</th><th>上传时间</th><th>上传者</th><th>操作</th>' +
                               '</tr></thead><tbody>';
                        
                        attachments.forEach(function(attachment) {
                            const fileSize = formatFileSize(attachment.fileSize);
                            const uploadTime = new Date(attachment.uploadTime).toLocaleString();
                            
                            html += '<tr>' +
                                '<td>' + attachment.originalFileName + '</td>' +
                                '<td>' + (attachment.fileType || '-') + '</td>' +
                                '<td>' + fileSize + '</td>' +
                                '<td>' + uploadTime + '</td>' +
                                '<td>' + attachment.uploadBy + '</td>' +
                                '<td>' +
                                '<a href="/risk-management/api/risk-attachments/download/' + attachment.id + '" class="btn btn-sm btn-info mr-1" title="下载"><i class="fa fa-download"></i></a>' +
                                '<button class="btn btn-sm btn-danger" onclick="deleteAttachment(' + attachment.id + ')" title="删除"><i class="fa fa-trash"></i></button>' +
                                '</td>' +
                                '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                    } else {
                        html = '<p class="text-center">暂无附件</p>';
                    }
                    
                    $('#attachment-container').html(html);
                },
                error: function() {
                    $('#attachment-container').html('<p class="text-center text-danger">加载附件数据失败</p>');
                }
            });
        }
        
        // 删除附件
        function deleteAttachment(attachmentId) {
            if (confirm('确定要删除此附件吗？')) {
                $.ajax({
                    url: '/risk-management/api/risk-attachments/' + attachmentId,
                    type: 'DELETE',
                    success: function() {
                        loadAttachments();
                    },
                    error: function() {
                        alert('删除附件失败');
                    }
                });
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 加载响应计划数据
        function loadResponsePlans() {
            $.ajax({
                url: '/risk-management/risk-response/list/' + riskId,
                type: 'GET',
                dataType: 'html',
                success: function(response) {
                    $('#response-plans-container').html(response);
                },
                error: function() {
                    $('#response-plans-container').html('<p class="text-center text-danger">加载响应计划数据失败</p>');
                }
            });
        }
        
        // 更新风险状态
        function updateStatus(status) {
            $.ajax({
                url: '/risk-management/risk/status/' + riskId + '/' + status,
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        alert('风险状态更新成功');
                        location.reload();
                    } else {
                        alert('风险状态更新失败：' + result.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        }
        
        // 指定责任人
        function assignOwner() {
            const ownerId = $('#ownerId').val();
            
            if (!ownerId) {
                alert('请选择责任人');
                return;
            }
            
            $.ajax({
                url: '/risk-management/risk/assign/' + riskId + '/' + ownerId,
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        alert('责任人指定成功');
                        location.reload();
                    } else {
                        alert('责任人指定失败：' + result.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        }
        
        // 确认删除
        function confirmDelete() {
            $('#deleteModal').modal('show');
        }
        
        // 删除风险
        function deleteRisk() {
            $.ajax({
                url: '/risk-management/risk/delete/' + riskId,
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        alert('风险删除成功');
                        window.location.href = '/risk-management/risk/project/' + projectId;
                    } else {
                        alert('风险删除失败：' + result.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        }
    </script>
</body>
</html> 